<template>
  <div class="add-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>知识管理</el-breadcrumb-item>
        <el-breadcrumb-item>新增文章</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 表单内容 -->
    <div class="page-content">
      <el-form 
        :model="articleForm" 
        :rules="formRules" 
        ref="articleForm"
        label-width="80px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="标题" prop="name">
              <el-input 
                v-model="articleForm.name" 
                placeholder="请输入文章标题"
                maxlength="100"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="标签">
              <div class="tags-container">
                <!-- 显示已选标签 -->
                <div class="selected-tags">
                  <el-tag
                    v-for="(tag, index) in articleForm.tags"
                    :key="index"
                    closable
                    @close="removeTag(index)"
                    style="margin-right: 8px; margin-bottom: 8px;"
                  >
                    {{ tag.name }}
                  </el-tag>
                </div>
                
                <!-- 添加新标签 -->
                <el-input
                  v-if="inputTagVisible"
                  v-model="inputTagValue"
                  ref="saveTagInput"
                  size="small"
                  style="width: 120px;"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm"
                  placeholder="输入标签名"
                ></el-input>
                <el-button 
                  v-else 
                  class="button-new-tag" 
                  size="small" 
                  @click="showInput"
                >
                  + 添加标签
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="内容" prop="content">
              <ExcalidrawComponent
                ref="excalidrawComponent"
                :resourceJson="excalidrawData"
                :darkMode="true"
                :viewMode="false"
                :gridMode="true"
                :zenMode="false"
                height="600px"
                @change="handleExcalidrawChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="page-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
    </div>
  </div>
</template>

<script>
import ExcalidrawComponent from "@/components/ExcalidrawComponent.vue";
import { deepClone } from "@/utils";
import * as knowledgeApi from '@/api/knowledge.api.js';
import { alertWithPaylod } from "@/utils/alertUtil";

export default {
  name: 'AddPage',
  components: {
    ExcalidrawComponent
  },
  data() {
    return {
      // 表单数据
      articleForm: {
        name: '',
        content: '',
        tags: []
      },
      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 100, message: '标题长度在 1 到 100 个字符', trigger: 'blur' }
        ]
      },
      // Excalidraw相关
      excalidrawData: null,
      jsonData: null,
      // 标签相关
      inputTagVisible: false,
      inputTagValue: '',
      // 状态
      saving: false
    }
  },
  methods: {
    /**
     * 处理Excalidraw内容变化
     * @param {Object} excalidrawData - Excalidraw数据
     */
    handleExcalidrawChange(excalidrawData) {
      this.jsonData = excalidrawData;
    },

    /**
     * 显示标签输入框
     */
    showInput() {
      this.inputTagVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    /**
     * 确认添加标签
     */
    handleInputConfirm() {
      const inputValue = this.inputTagValue.trim();
      if (inputValue && !this.articleForm.tags.some(tag => tag.name === inputValue)) {
        this.articleForm.tags.push({ name: inputValue });
      }
      this.inputTagVisible = false;
      this.inputTagValue = '';
    },

    /**
     * 移除标签
     * @param {number} index - 标签索引
     */
    removeTag(index) {
      this.articleForm.tags.splice(index, 1);
    },

    /**
     * 保存文章
     */
    async handleSave() {
      // 表单验证
      const valid = await this.$refs.articleForm.validate().catch(() => false);
      if (!valid) {
        return;
      }

      this.saving = true;
      try {
        // 准备保存数据
        const params = deepClone(this.articleForm);
        params.excalidraw = this.jsonData;

        // 调用API保存
        const result = await knowledgeApi.add(params);
        alertWithPaylod(result);

        if (result?.success) {
          this.$message.success('文章保存成功！');
          // 保存成功后跳转到知识列表页面
          this.$router.push('/knowledge/list');
        }
      } catch (error) {
        console.error('保存文章失败:', error);
        this.$message.error('保存失败，请重试');
      } finally {
        this.saving = false;
      }
    },

    /**
     * 取消操作
     */
    handleCancel() {
      // 检查是否有未保存的内容
      const hasContent = this.articleForm.name || 
                        this.articleForm.tags.length > 0 || 
                        this.jsonData;

      if (hasContent) {
        this.$confirm('确定要取消吗？未保存的内容将丢失。', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '继续编辑',
          type: 'warning'
        }).then(() => {
          this.$router.go(-1);
        }).catch(() => {
          // 用户选择继续编辑，不做任何操作
        });
      } else {
        this.$router.go(-1);
      }
    }
  }
}
</script>

<style scoped>
.add-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-content {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.tags-container {
  min-height: 32px;
}

.selected-tags {
  display: inline-block;
  margin-right: 8px;
}

.button-new-tag {
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.page-actions {
  text-align: right;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-actions .el-button {
  margin-left: 10px;
}
</style>